import { AdminModel } from '~/server/models/admin.model';

// 验证登录
export default defineEventHandler(async (event): Promise<any> => {
	if (
		event.path.includes('/api/admin') &&
		event.path !== '/api/admin/user/login' &&
		event.path !== '/api/admin/user/create'
	) {
		const cookieToken = getCookie(event, 'token');

		if (!cookieToken || !cookieToken.includes('Bearer ')) {
			return {
				code: 0,
				message: '请先登录',
			};
		}

		// 获取 Token
		const token: string = cookieToken.replace('Bearer ', '');

		try {
			// 验证 Token
			const verify: any = await verifyToken(token);

			// 验证用户是否存在
			const findUser = await AdminModel.findById(verify.id);

			if (!findUser) {
				return {
					code: 0,
					message: '用户不存在',
				};
			}
		} catch (error: any) {
			return {
				code: 0,
				message: error.message,
			};
		}
	}
});
